<template>
  <div>
    <!-- 公告邮件 -->
    <el-dialog :visible.sync="isShow" v-if="isShow" title="公告邮件" width="55%" :before-close="handleClose" top="50px" :close-on-click-modal="false" modal-append-to-body>
      <el-row :gutter="24">
        <div class="border-box">
          <el-form ref="mailForm" :model="formParams" :rules="ruleForm" label-position="right" label-width="90px">
            <el-form-item label="公告邮件类型:" prop="type" label-width="120px">
              <el-radio-group v-model="formParams.type">
                <el-radio-button :label="1">公告</el-radio-button>
                <el-radio-button :label="2">邮件</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <div class="border-item-shadow">
              <div class="box-title">公告邮件内容:</div>
              <el-col :span="12">
                <el-form-item label="公告邮件标题:" prop="title_type" label-width="120px">
                  <el-radio-group v-model="formParams.title_type">
                    <el-radio :label="1">自定义</el-radio>
                    <el-radio :label="0">选择后台多语言</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div v-show="formParams.title_type==1">
                  <el-form-item label="选择多语言:" label-width="100px">
                    <el-select class="width80" v-model="multilingualTitleData" placeholder="请选择多语言" multiple clearable filterable @change="chooseTitleItem">
                      <el-option :label="second.label" :value="second.key" v-for="(second, two) in LANG_DATA" :key="two"></el-option>
                    </el-select>
                  </el-form-item>
                  <div class="prooItem width80" v-for="(item, index) in chooseTitleDataList" :key="index">
                    <p style="margin: 0;font-size: 15px;">{{ item.label }}</p>
                    <el-input type="textarea" :rows="2" v-model="item.lang" placeholder="请输入内容"></el-input>
                  </div>
                </div>
                <el-form-item v-show="formParams.title_type==0" label="选择公告邮件标题:" prop="title_id" label-width="140px">
                  <el-select class="width80" v-model="formParams.title_id" placeholder="请选择公告邮件标题" filterable>
                    <el-option :label="second.c_base_zh_cn" :value="second.a_base_message_id" v-for="(second, two) in languageData" :key="two"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公告邮件内容:" prop="content_type" label-width="120px">
                  <el-radio-group v-model="formParams.content_type">
                    <el-radio :label="1">自定义</el-radio>
                    <el-radio :label="0">选择后台多语言</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div v-show="formParams.content_type==1">
                  <el-form-item label="选择多语言:" label-width="100px">
                    <el-select class="width80" v-model="multilingualContentData" placeholder="请选择多语言" multiple clearable filterable @change="chooseContentItem">
                      <el-option :label="second.label" :value="second.key" v-for="(second, two) in LANG_DATA" :key="two"></el-option>
                    </el-select>
                  </el-form-item>
                  <div class="prooItem width80" v-for="(item, index) in chooseContentDataList" :key="index">
                    <p style="margin: 0;font-size: 15px;">{{ item.label }}</p>
                    <el-input type="textarea" :rows="2" v-model="item.lang" placeholder="请输入内容"></el-input>
                  </div>
                </div>
                <el-form-item v-show="formParams.content_type==0" label="选择公告邮件内容:" prop="content_id" label-width="140px">
                  <el-select class="width80" v-model="formParams.content_id" placeholder="请选择公告邮件内容" filterable>
                    <el-option :label="second.c_base_zh_cn" :value="second.a_base_message_id" v-for="(second, two) in languageData" :key="two"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="公告邮件备注:" prop="remarks" label-width="110px">
                  <el-input class="width40" type="text" v-model="formParams.remarks" clearable placeholder="请输入公告邮件备注"></el-input>
                </el-form-item>
              </el-col>
            </div>
            <div class="border-item-shadow">
              <div class="box-title">基本信息:</div>
              <el-col :span="12">
                <el-form-item label="用户ID:" prop="send_user_id">
                  <el-input type="text" v-model="formParams.send_user_id" clearable placeholder="多个用户,用英文的分号隔开"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="测试用户ID:" prop="test_send_user_id">
                  <el-input type="text" v-model="formParams.test_send_user_id" clearable placeholder="多个用户,用英文的分号隔开"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="跳转链接:" prop="jump_url">
                  <el-input type="text" v-model="formParams.jump_url" clearable placeholder="请输入公告邮件跳转链接"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公告邮件图片:" prop="pic" label-width="110px">
                  <imgUpLoad :url="formParams.pic" @success='imgUploadChangIcon' />
                </el-form-item>
              </el-col>
            </div>
            <div class="border-item-shadow">
              <div class="box-title">公告邮件时间:</div>
              <el-col :span="24">
                <el-form-item label="是否延迟发送:" prop="is_delay_send" label-width="110px">
                  <el-radio-group v-model="formParams.is_delay_send">
                    <el-radio :label="1">定时发送</el-radio>
                    <el-radio :label="0">单次发送</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item v-if="formParams.is_delay_send" label="定时发送时间:" prop="delay_send_time_str" label-width="110px">
                  <el-date-picker is-range v-model="formParams.delay_send_time_str" type="datetime" placeholder="选择定时发送日期时间" class="full-width-input time-box" clearable></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="展示截止时间:" prop="effect_time_str" label-width="120px">
                  <el-date-picker is-range v-model="formParams.effect_time_str" type="datetime" placeholder="选择立即发送日期时间" class="full-width-input time-box" clearable></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户接收截止时间:" prop="receive_end_time_str" label-width="140px">
                  <el-date-picker is-range v-model="formParams.receive_end_time_str" type="datetime" placeholder="选择立即发送日期时间" class="full-width-input time-box" clearable></el-date-picker>
                </el-form-item>
              </el-col>
            </div>
            <!-- 玩家筛选 -->
            <div class="border-item-shadow">
              <p class="box-title">玩家筛选:</p>
              <div class="flex" v-for="(item,index) in filterData" :key="index">
                <div class="btn-box-add">
                  <el-tooltip content="新增条件筛选" v-show="filterIndex==index && filterIndex < 1">
                    <el-button class="marginL10" size="mini" type="primary" circle icon="el-icon-plus" @click="addCondition" />
                  </el-tooltip>
                </div>
                <el-form-item label="选择条件:" label-width="80px">
                  <el-select v-model="item.filter_type" placeholder="请选择玩家筛选条件" filterable>
                    <el-option :label="second.label" :value="second.value" v-for="(second, two) in conditionData" :key="two"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="选择筛选条件:" label-width="110px">
                  <el-select v-model="item.filter_condition" placeholder="请选择玩家筛选条件" filterable>
                    <el-option :label="second.label" :value="second.value" v-for="(second, two) in conditionFilterData" :key="two"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="筛选的值:">
                  <el-input-number :min="0" :max="999999999" :precision="0" v-model="item.filter_value" controls-position="right" clearable placeholder="请输入道具数量"  />
                </el-form-item>
                <div class="btn-box-delete" label-width="60px">
                  <el-tooltip content="删除配置" v-show="filterData.length != 1">
                    <el-button class="marginL10" size="mini" type="danger" circle icon="el-icon-minus" @click="deleteCondition(index)" />
                  </el-tooltip>
                </div>
              </div>
            </div>
            <!-- 选择道具 -->
            <div class="border-item-shadow">
              <p class="box-title">道具配置:</p>
              <div class="flex" v-for="(item,index) in propData" :key="index">
                <div class="btn-box-add">
                  <el-tooltip content="新增道具配置" v-show="propIndex==index">
                    <el-button class="marginL10" size="mini" type="primary" circle icon="el-icon-plus" @click="addProp" />
                  </el-tooltip>
                </div>
                <el-form-item label="选择道具:">
                  <el-select v-model="item.type" placeholder="请选择道具类型" filterable>
                    <el-option :label="second.label" :value="second.value" v-for="(second, two) in propDataArray" :key="two"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="数量:">
                  <el-input-number :min="0" :max="999999999" :precision="0" v-model="item.num" controls-position="right" clearable placeholder="请输入道具数量"  />
                </el-form-item>
                <div class="btn-box-delete" label-width="60px">
                  <el-tooltip content="删除配置" v-show="propData.length != 1">
                    <el-button class="marginL10" size="mini" type="danger" circle icon="el-icon-minus" @click="deleteProp(index)" />
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleClose">取 消</el-button>
        <el-button size="medium" type="primary" @click="handleConfirm('mailForm')">确 认</el-button>
      </span>
    </el-dialog>
    <GoogleCheck ref="GoogleCheck" :show="googleCheckShow" :type="4" @handleConfirm="handleConfirm('mailForm')" @handleClose="handleQrClose"/>
  </div>
</template>

<script>
import {
  addMail,
  editMail
} from "@/api/config";
import {
  LANG_DATA,
  LANG_FORM
} from '@/utils/enum'
import {
  addAdminMultilingual
} from '@/api/game'
import imgUpLoad from '@/components/imgUpLoadSingle'
import GoogleCheck from '@/components/GoogleCheck'
export default {
  components: {
    imgUpLoad,
    GoogleCheck
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: function () {
        return {}
      }
    },
    languageArray: {
      type: Array,
      default: function () {
        return []
      }
    },
    propDataArray: {
      type: Array,
      default: function () {
        return []
      }
    },
  },
  data () {
    return {
      LANG_DATA,
      LANG_FORM,
      isShow: false,
      googleCheckShow: false,
      propData: [{
        type: '',
        num: 0
      }],
      filterData: [
        { filter_type: 1, filter_condition: '', filter_value: 0 }
      ],
      filterIndex: 0,
      conditionData: [
        { label: '玩家ID', value: 1 },
        { label: 'VIP等级', value: 2 },
      ],
      conditionFilterData: [
        { label: '大于', value: '>' },
        { label: '等于', value: '=' },
        { label: '大于等于', value: '>=' },
        { label: '小于等于', value: '<=' },
      ],
      multilingualTitleData: [],
      multilingualContentData: [],
      chooseTitleDataList: [],
      chooseContentDataList: [],
      propIndex: 0,
      languageData: [],
      formParams: {
        type: 2,
        title_id: '',
        title_type: 0,
        content_id: '',
        content_type: 0,
        remarks: '',
        items: '',
        send_user_id: '',
        test_send_user_id: '',
        delay_send_time_str: '',
        jump_url: '',
        pic: '',
        filter_json: '',
        effect_time_str: '',
        receive_end_time_str: '',
        delay_send_time_str: '',
        is_delay_send: 0,
      },
      ruleForm: {
        title_type: [{ required: true, trigger: 'blur', message: '请选择公告邮件标题', }],
        content_type: [{ required: true, trigger: 'blur', message: '请选择公告邮件内容', }],
        effect_time_str: [{ required: true, trigger: 'blur', message: '请选择公告邮件保存有效期', }],
        receive_end_time_str: [{ required: true, trigger: 'blur', message: '请选择可接收截止注册时间', }],
      },
      langForm: LANG_FORM
    }
  },
  computed: {},
  watch: {
    show: function () {
      let that = this;
      that.isShow = that.show
      if (that.data) {
        that.data.title_type = 0
        that.data.content_type = 0
        that.formParams = JSON.parse(JSON.stringify(that.data))
        if (that.formParams.filter_json) {
          that.filterData = that.formParams.filter_json
        }
        if (that.formParams.items) {
          that.propData = that.formParams.propData
        }
      } else {
        that.formParams = {
          type: 2,
          title_id: '',
          title_type: 0,
          content_id: '',
          content_type: 0,
          remarks: '',
          items: '',
          send_user_id: '',
          test_send_user_id: '',
          delay_send_time_str: '',
          jump_url: '',
          pic: '',
          filter_json: '',
          effect_time_str: '',
          receive_end_time_str: '',
          delay_send_time_str: '',
          is_delay_send: 0,
        }
        that.propData = [{ type: '', num: 0 }]
        that.filterData = [{ filter_type: 1, filter_condition: '', filter_value: 0 }]
        that.filterIndex = 0
      }
    },
    languageArray: {
      handler (newVal) {
        let that = this;
        if (newVal) {
          that.languageData = newVal
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted () { },
  methods: {
    // 确认
    async handleConfirm (formvalue) {
      let that = this, noData = [], params = JSON.parse(JSON.stringify(that.formParams));
      // 公告邮件标题
      if (params.title_type) {
        if (!that.titleEnglishExist()) {
          return that.$message.error('请输入邮件标题英语对应的语言内容')
        }
        await that.getLangId(that.langConfirm(that.chooseTitleDataList)).then(res => {
          return params.title_id = res
        })
      }
      // 公告邮件内容
      if (params.content_type) {
        if (!that.contentEnglishExist()) {
          return that.$message.error('请输入邮件内容英语对应的语言内容')
        }
        await that.getLangId(that.langConfirm(that.chooseContentDataList)).then(res => {
          return params.content_id = res
        })
      }
      // 公告邮件时间
      params.effect_time_str = that.$public.standardDate(params.effect_time_str)
      params.receive_end_time_str = that.$public.standardDate(params.receive_end_time_str)
      if(new Date(params.receive_end_time_str).getTime() > new Date(params.receive_end_time_str).getTime()){
        return that.$message.error('用户接收截止时间必须小于邮件展示截止时间')
      }
      // 定时发送
      if (params.is_delay_send && !params.delay_send_time_str) {
        return that.$message.error('请选择定时发送时间')
      } else if (params.is_delay_send && params.delay_send_time_str) {
        params.delay_send_time_str = that.$public.standardDate(params.delay_send_time_str)
        if (new Date(params.delay_send_time_str).getTime() >= new Date(params.effect_time_str).getTime()) {
          return that.$message.error('公告邮件发送时间不能大于等于公告邮件保存有效时间')
        }
        if (new Date(params.delay_send_time_str).getTime() >= new Date(params.receive_end_time_str).getTime()) {
          return that.$message.error('公告邮件发送时间不能大于等于公告邮件截止时间')
        }
        if (new Date(params.delay_send_time_str).getTime() <= new Date().getTime()) {
          return that.$message.error('公告邮件发送时间不能小于等于当前时间')
        }
      } else {
        params.delay_send_time_str = ''
      }
      // 道具配置
      that.propData.map(item => {
        if (!item.type) {
          noData.push(item)
        }
      })
      if (noData.length) {
        params.items = ''
      } else {
        params.items = that.propSet(that.propData)
      }
      // 处理玩家筛选
      params.filter_json = that.filterData
      // // 谷歌验证码
      // if (!that.$refs.GoogleCheck.formParams.google_code) {
      //   return that.googleCheckShow = true
      // } else {
      //   that.googleCheckShow = false
      // }
      that.$refs[formvalue].validate(async (valid) => {
        if (valid) {
          if (!params.id) {
            addMail(params).then(function (res) {
              that.$message.success(res.msg)
              that.$emit('onHideDetails', true)
            }).catch((error) => {
              that.$message.error(error.msg)
            })
          } else {
            editMail(params).then(function (res) {
              that.$message.success(res.msg)
              that.$emit('onHideDetails', true)
            }).catch((error) => {
              that.$message.error(error.msg)
            })
          }
        } else {
          return false;
        }
      });
    },
    // 新增多语言
    langConfirm (arr) {
      let langKey = [], langValue = {}, noData = [];
      langKey = Object.keys(this.langForm)
      arr.map(item => {
        langKey.map(first => {
          if (item.key == first && item.lang) {
            langValue[first] = item.lang
          }
        })
        if (!item.lang) {
          noData.push(item)
        }
      })
      return langValue
    },
    getLangId (langValue) {
      return new Promise((resolve, reject) => {
        addAdminMultilingual(langValue).then(function (res) {
          if (res.code) {
            resolve(res.data)
          }
        }).catch((error) => {
          this.$message.error(error.msg)
        })
      })
    },
    chooseTitleItem (val) {
      let that = this;
      that.chooseTitleDataList = []
      that.LANG_DATA.map(item => {
        val.map(first => {
          if (item.key == first) {
            that.chooseTitleDataList.push({ label: item.label, key: item.key, lang: '' })
          }
        })
      })
    },
    chooseContentItem (val) {
      let that = this;
      that.chooseContentDataList = []
      that.LANG_DATA.map(item => {
        val.map(first => {
          if (item.key == first) {
            that.chooseContentDataList.push({ label: item.label, key: item.key, lang: '' })
          }
        })
      })
    },
    // 新增条件筛选
    addCondition () {
      this.filterIndex++
      this.filterData.push({
        filter_type: 1,
        filter_condition: '',
        filter_value: 0
      })
    },
    // 删除条件筛选
    deleteCondition (index) {
      this.filterIndex--
      this.filterData.splice(index, 1,)
    },
    // 新增道具
    addProp () {
      this.propIndex++
      this.propData.push({
        type: '',
        num: 0
      })
    },
    // 删除道具
    deleteProp (index) {
      this.propIndex--
      this.propData.splice(index, 1,)
    },
    // 道具设置
    propSet (arr) {
      let reward = '';
      arr.map(item => {
        reward += item.type + ',' + this.$public.mathNumberMultiply(item.num, 10000) + ';'
      })
      reward = reward.substring(0, reward.length - 1)
      return reward
    },
    // 上传图片
    imgUploadChangIcon (url) {
      this.formParams.pic = url
    },
    // 是否有英语
    titleEnglishExist () {
      return (this.chooseTitleDataList.find((item) => item.key === 'c_base_en_us')?.lang || '')
    },
    contentEnglishExist () {
      return (this.chooseContentDataList.find((item) => item.key === 'c_base_en_us')?.lang || '')
    },
    // 取消谷歌验证
    handleQrClose(){
      this.googleCheckShow = false
    },
    // 取消
    handleClose () {
      this.handleQrClose()
      this.$emit('onHideDetails', false)
    },
  }
}
</script>

<style scoped lang="scss">
.border-item {
  padding: 10px;
}
.box-title {
  font-size: 17px;
  font-weight: 600;
}
.btn-box-add {
  width: 50px;
  margin-bottom: 20px;
  margin-right: 10px;
  text-align: center;
  .el-button {
    height: 28px;
  }
}
.btn-box-delete {
  width: 50px;
  margin-bottom: 20px;
  text-align: center;
  .el-button {
    height: 28px;
  }
}
.prooItem {
  margin: 10px;
}
</style>